<?php


namespace app\api\controller\activity;

use addons\xyb\XypHelper;
use app\api\controller\xyb\Base;

use app\api\service\Activity\AssociationJobsDetectionService;
use app\api\service\Activity\AssociationJobsService;
use app\api\service\Activity\AssociationService;
use app\api\service\UsersService;
use app\common\model\daily\UsersScoreLogModel;
use app\common\model\marketing\Association as AssociationModel;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\marketing\UsersMarketingCoupons;
use think\Cache;
use think\Db;

class Association extends Base
{
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 显示用户参与的社团列表
     *
     * 该方法首先获取当前已认证的用户信息，然后调用AssociationService中的方法
     * 获取该用户参与的社团列表，并返回成功响应及社团列表数据
     */
    public function index()
    {
        // 获取当前已认证的用户信息
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);

        // 调用AssociationService方法，获取用户参与的社团列表
        $res = AssociationService::getUsersParticipateAssociationLists($users->id, $user_circle['circle_id']);

        // 返回成功响应及社团列表数据
        $this->success('请求成功', $res);
    }

    /**
     * 获取用户参与社团活动的详细信息
     *
     * 此方法主要用于获取用户在特定社团活动中的详细信息它首先检查请求中是否提供了有效的社团ID，
     * 如果没有提供或提供的是无效ID，则显示错误信息接下来，获取当前授权的用户信息，
     * 并调用AssociationService中的方法来获取社团活动详情最后，如果请求成功，
     * 则使用成功信息和数据响应用户
     */
    public function details()
    {
        // 使用框架的参数验证功能，确保 id 参数为正整数
        $params = request()->param();
        $validate = new \think\Validate([
            'id' => 'require|integer|gt:0',
        ]);
//        if (!$validate->check($params)) {
//            $this->error('参数错误');
//        }
        $association_id = (int)$params['id']?$params['id']:31;
        // 获取当前授权的用户信息，用于后续的查询和验证
        // 注意：getAuthUsers 方法已优化，使用缓存减少数据库查询次数
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        // 调用服务层方法，获取用户参与的社团活动详细信息
        $res = AssociationService::getUsersParticipateAssociationDetails($association_id, $users->id, $user_circle['circle_id']);
        // 返回成功响应，包括成功信息和查询结果
        $this->success('请求成功', $res);
    }

    /**
     * 用户报名任务
     *
     * 该方法用于用户报名任务，它首先检查请求中是否提供了有效的社团ID，
     * 如果没有提供或提供的是无效ID，则显示错误信息接下来，获取当前授权的用户信息，
     * 并调用AssociationService中的方法来获取社团活动详情最后，如果请求成功，
     * 则使用成功信息和数据响应用户
     */
    public function task_enroll()
    {
        $params = request()->param();
        $validate = new \think\Validate([
            'id' => 'require|integer|gt:0',
        ]);
        if (!$validate->check($params)) {
            $this->error('参数错误');
        }
        $association_id = (int)$params['id'];
        $cache_key = 'task_enroll_' . $association_id;
        if (Cache::get($cache_key)) {
            $this->error('请求过于频繁，请稍后再试');
        }
        Cache::set($cache_key, $association_id, 5);
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        $res = AssociationService::usersEnrollAssociationTask($association_id, $users->id, $user_circle['circle_id']);
        if (!$res || !$res['code'] || $res['code'] == 0) {
            Cache::rm($cache_key);
            $this->error($res['msg']);
        }
        Cache::rm($cache_key);
        $this->success('报名成功', $res);
    }

    /*获取每日任务列表*/
    public function get_daily_tasks(){
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        // 调用AssociationService方法，获取用户参与的社团列表
        $res = AssociationService::getUsersParticipateDailyAssociationLists($users->id, $user_circle['circle_id']);
        // 返回成功响应及社团列表数据
        $this->success('请求成功', $res);
    }

    /*获取首页推荐任务*/
    public function get_daily_recommend_tasks(){
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        // 调用AssociationService方法，获取用户参与的社团列表
        $res = AssociationService::getUsersParticipateDailyAssociationRecommendLists($users->id, $user_circle['circle_id']);
        // 返回成功响应及社团列表数据
        $this->success('请求成功', $res);
    }

    /*获取用户任务记录列表*/
    public function get_daily_participation(){
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);

        // 获取用户参与每日任务列表
        $res = AssociationService::getUsersParticipateDailyLists($users->id, $user_circle['circle_id']);

        // 返回成功响应及社团列表数据
        $this->success('请求成功', $res);
    }

    /*领取任务发放的优惠劵*/
    public function users_receive_jobs_rewards()
    {
        $progress_id = $this->request->request('jobs_id', 0);

        $users = $this->getAuthUsers();

        AssociationJobsService::distributeJobsCouponsRewards($users->id, $progress_id);

        $this->success('领取成功');
    }

    /*获取用户奖励汇总*/
    public function get_users_reward()
    {
        $users = $this->getAuthUsers();
        $response = [
            'point' => [
                'current'       =>  $users->score,
                'accumulate'    => UsersScoreLogModel::getUsersCatWayTotal($users->id, 'score', 1),
                'consumption'   => UsersScoreLogModel::getUsersCatWayTotal($users->id, 'score', 2)
            ],
            'youth' => [
                'current'       => $users->youth_coin,
                'accumulate'    => UsersScoreLogModel::getUsersCatWayTotal($users->id, 'youth_coin', 1),
                'consumption'   => UsersScoreLogModel::getUsersCatWayTotal($users->id, 'youth_coin', 2)
            ],
//            'coupons' => [
//                'current'       => UsersMarketingCoupons::getUsersCouponsSourceTotal($users->id, 3,1),
//                'accumulate'    => UsersMarketingCoupons::getUsersCouponsSourceTotal($users->id, 3),
//                'consumption'   => 0
//            ],
        ];
        $this->success('请求成功', $response);
    }

    public function get_users_reward_detail()
    {
        $users = $this->getAuthUsers();
        $type = (int)$this->request->request('type', 1);
        if($type === 3){
            $response = UsersMarketingCoupons::getUsersCouponsSourceLists($users->id, 2);
        }else {
            $response = UsersScoreLogModel::getUsersCatLists($users->id, $type);
        }
        $this->success('请求成功', $response);
    }

    public function detection()
    {
       $res = AssociationJobsDetectionService::index(36, 1926);
        $this->success('报名成功', $res);
    }

    public function rule()
    {
        $res = AssociationModel::submitDailyConfigSetupContent(1, '', 'get');
        $this->success('success', ['content' => $res]);
    }
}